package com.college.resource.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.college.common.utils.HttpUtil;
import com.college.resource.service.FileService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hc.client5.http.entity.mime.ContentBody;
import org.apache.hc.client5.http.entity.mime.FileBody;
import org.apache.hc.client5.http.entity.mime.StringBody;
import org.apache.hc.core5.http.ContentType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class FileServiceImpl implements FileService {

    @Value("${userFilePath}")
    private String userFilePath;

    @Override
    public String uploadFile(MultipartFile multipartFile, String fileName){
        String pushUrl = "http://110.41.136.218:8000/upload.php";
        Map<String, ContentBody> reqParam = new HashMap<>();

        File file;
        try {
            String prefix = fileName.substring(fileName.lastIndexOf("."));
            file = File.createTempFile(fileName, prefix);
            multipartFile.transferTo(file);
            //删除临时文件
            file.deleteOnExit();

            if (ObjectUtils.isEmpty(file)){
                return null;
            }
            reqParam.put("file", new FileBody(file));
            reqParam.put("upload_path", new StringBody("/www/wwwroot/file/other", ContentType.MULTIPART_FORM_DATA));
            String respond = HttpUtil.syncPostData(pushUrl, reqParam);

            if (StringUtils.isBlank(respond)){
                return null;
            }
            JSONObject respondJson = JSONObject.parseObject(respond);
            Boolean success = respondJson.getBoolean("success");
            if (Boolean.TRUE.equals(success)){
                return respondJson.getString("filename");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
